import {PureComponent} from "react";
import {Input, Tabs, BackTop} from 'antd';
import React from "react";
import {connect} from "react-redux";
import {actionCreators} from "../store";
import {Table, Button, Loading, Message} from 'element-react';
import moment from "moment";
import emitter from '../../../common/events'
import '../style.css'

const Search = Input.Search;
const TabPane = Tabs.TabPane;

class ContentListComponent extends PureComponent {

    componentDidMount() {
        emitter.on('changeMenuItem', (msg) => {
            this.getTypeData(msg);
        });
    }

    getTypeData(type) {
        let prefix = '';
        switch (type) {
            case 'machine':
                prefix = 'gowild_eve_robot_normal';
                break;
            case 'u3d':
                prefix = 'gowild_eve_robot_u3d';
                break;
            case 'android':
                prefix = 'gowild_eve_android';
                break;
            case 'iOS':
                prefix = 'gowild_eve_ios';
                break;
            default:
                break
        }
        this.setState({
            'prefix': prefix
        }, () => {
            let json = {
                "limit": 30,
                "marker": '',
                "prefix": this.state.prefix
            };
            this.props.getLogFileList(json, (msg) => {
                Message.success({
                    message: msg
                });
                //更新当前tabs
                this.setState({'panes': this.state.panes, 'activeKey': this.state.panes[0].key});
                window.scrollTo(0, 0);
            });
        });
    }

    nextPage = () => {
        const {nextMarker} = this.props;
        this.loadData(nextMarker, this.state.prefix);
    };

    firstPage = () => {
        this.loadData('', this.state.prefix);
    };

    loadData(marker, prefix) {
        let json = {
            "limit": 30,
            "marker": marker,
            "prefix": prefix
        };
        this.props.getLogFileList(json, (msg) => {
            Message.success({
                message: msg
            });
            window.scrollTo(0, 0);
        });
    }

    onSearch = (value, event) => {
        this.loadData('', value);
    };

    onChangeTabs = (activeKey) => {
        this.setState({activeKey});
    };

    onEditTabs = (targetKey, action) => {
        this[action](targetKey);
    };

    add = (content) => {
        const panes = this.state.panes;
        const activeKey = `newTab_${this.newTabIndex++}`;
        panes.push({title: `解析结果${this.newTabIndex}`, content: content, key: activeKey});
        this.setState({panes, activeKey});
    };

    remove = (targetKey) => {
        let activeKey = this.state.activeKey;
        let lastIndex = -1;
        this.state.panes.forEach((pane, i) => {
            if (pane.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        const panes = this.state.panes.filter(pane => pane.key !== targetKey);
        if (panes.length && activeKey === targetKey) {
            if (lastIndex >= 0) {
                activeKey = panes[lastIndex].key;
                if (lastIndex === 0) {
                    //还原索引
                    this.newTabIndex = 0;
                }
            } else {
                activeKey = panes[0].key;
            }
        }
        this.setState({panes, activeKey});
    };

    constructor(props) {
        super(props);
        this.newTabIndex = 0;
        const panes = [
            {title: '日志列表', key: 'tab_1', closable: false}
        ];
        this.state = {
            prefix: '',
            panes,
            activeKey: panes[0].key,
            columns: [
                {
                    label: "CreateTime",
                    prop: "CreateTime",
                    width: 180,
                    fixed: 'left',
                    align: 'center',
                    sortable: true,
                    render: (row, column, index) => {
                        return <span>{moment(row.CreateTime * 1000).format('YYYY/MM/DD HH:mm')}</span>
                    }
                },
                {
                    label: "BucketName",
                    prop: "BucketName",
                    width: 150,
                    align: 'center'
                },
                {
                    label: "FileName",
                    prop: "FileName",
                    width: 700
                },
                {
                    label: "Hash",
                    prop: "Hash",
                    width: 400
                },
                {
                    label: "MimeType",
                    prop: "MimeType",
                    width: 150,
                    align: 'center'
                },
                {
                    label: "first_object",
                    prop: "first_object",
                    width: 400
                },
                {
                    label: "Size",
                    prop: "Size",
                    width: 150,
                    sortable: true,
                    align: 'center'
                },
                {
                    label: "ModifyTime",
                    prop: "ModifyTime",
                    align: 'center',
                    width: 180,
                    sortable: true,
                    render: (row, column, index) => {
                        return <span>{moment(row.CreateTime * 1000).format('YYYY/MM/DD HH:mm')}</span>
                    }
                },
                {
                    label: "操作",
                    width: 250,
                    fixed: 'right',
                    align: 'center',
                    render: (row, column, index) => {
                        let suffix = '';
                        row.FileName.split('.').forEach(v => {
                            suffix = v
                        });
                        if (suffix === 'xlog') {
                            return (
                                <Button.Group>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.readFile(row)
                                    }}>查看</Button>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.downloadParsFile(row)
                                    }}>解析下载</Button>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.downloadFile(row)
                                    }}>源下载</Button>
                                    <Button type="primary" size="small" icon="delete" onClick={() => {
                                        this.deleteFile(row)
                                    }}/>
                                </Button.Group>
                            );
                        } else if (suffix.toUpperCase() === 'JPG' ||
                            suffix.toUpperCase() === 'PNG' ||
                            suffix.toUpperCase() === 'JPEG' ||
                            suffix.toUpperCase() === 'WEBP' ||
                            suffix.toUpperCase() === 'BMP' ||
                            suffix.toUpperCase() === 'OGG' ||
                            suffix.toUpperCase() === 'MP4') {
                            return (
                                <Button.Group>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.downloadFile(row)
                                    }}>源下载</Button>
                                    <Button type="primary" size="small" icon="delete" onClick={() => {
                                        this.deleteFile(row)
                                    }}/>
                                </Button.Group>
                            );
                        } else {
                            return (
                                <Button.Group>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.readFile(row)
                                    }}>查看</Button>
                                    <Button type="primary" size="small" onClick={() => {
                                        this.downloadFile(row)
                                    }}>源下载</Button>
                                    <Button type="primary" size="small" icon="delete" onClick={() => {
                                        this.deleteFile(row)
                                    }}/>
                                </Button.Group>
                            );
                        }
                    }
                }
            ]
        };
    }

    readFile = (row) => {
        let json = {
            "fileName": row.FileName,
        };
        this.props.readLogParsFile(json, (msg) => {
            Message.success({
                message: msg
            });
        }, (result) => {
            this.add(result.toString());
            window.scrollTo(0, 0);
        });
    };

    downloadParsFile = (row) => {
        let json = {
            "fileName": row.FileName,
        };
        this.props.downloadLogParsFile(json, (msg) => {
            Message.success({
                message: msg
            });
        });
    };

    downloadFile = (row) => {
        let json = {
            "fileName": row.FileName,
        };
        this.props.downloadLogFile(json, (msg) => {
            Message.success({
                message: msg
            });
        });
    };

    deleteFile = (row) => {
        let json = {
            "fileName": row.FileName,
        };
        this.props.deleteLogFile(json, (msg) => {
            Message.success({
                message: msg
            });
            this.firstPage();
        });
    };

    render() {
        const {dataSet, loading, nextMarker} = this.props;
        let loadingT = loading;
        if (loadingT === undefined) {
            loadingT = false;
        }
        let nextPage = false;
        if (nextMarker !== undefined) {
            nextPage = true;
        }
        return (
            <Loading loading={loadingT}>
                <BackTop/>
                <Tabs
                    onChange={this.onChangeTabs}
                    activeKey={this.state.activeKey}
                    type="editable-card"
                    onEdit={this.onEditTabs}
                >
                    {this.state.panes.map((pane) => {
                        if (pane.key === 'tab_1') {
                            return <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                                <Search
                                    className="input_search"
                                    placeholder="输入文件名前缀(可以搜索hpc2仓库下所有文件) 回车即可"
                                    onSearch={this.onSearch}
                                    enterButton="Search"
                                    size="large"
                                />
                                <Table
                                    style={{width: '100%'}}
                                    columns={this.state.columns}
                                    data={dataSet}
                                    border={true}
                                    stripe={true}
                                />
                                <Button.Group className='btnConfirmGroup'>
                                    <Button type="primary" icon="arrow-left" onClick={this.firstPage}>首页</Button>
                                    <Button type="primary" disabled={!nextPage} onClick={this.nextPage}>下一页<i
                                        className="el-icon-arrow-right el-icon-right"/></Button>
                                </Button.Group>
                            </TabPane>
                        } else {
                            let arr = pane.content.split('\r\n');
                            if (arr.length <= 1) {
                                arr = pane.content.split('\n');
                                if (arr.length <= 1) {
                                    arr = pane.content.split('\r');
                                    if (arr.length <= 1) {
                                        arr = [pane.content];
                                    }
                                }
                            }
                            return <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                                <div className='pane_content'>
                                    {
                                        arr.map((value, index) => {
                                            return <div key={index} className='pane_content_div'>
                                                <p>{index}</p>
                                                {/*这里是中文空格*/}
                                                <p className='pane_content_p'>{value.trim().length <= 0 ? '　' : value}</p>
                                                <hr/>
                                            </div>
                                        })
                                    }
                                </div>
                            </TabPane>
                        }
                    })}
                </Tabs>
            </Loading>
        );
    }
}

const mapState = (state) => ({
    dataSet: state.getIn(['home', 'logInfo', 'DataSet']),
    loading: state.getIn(['home', 'loading']),
    readContent: state.getIn(['home', 'readContent']),
    nextMarker: state.getIn(['home', 'logInfo', 'NextMarker']),
});

const mapDispatch = (dispatch) => ({
    getLogFileList(json, func) {
        dispatch(actionCreators.getLogFileList(json, func))
    },
    downloadLogFile(json, func) {
        dispatch(actionCreators.downloadLogFile(json, func))
    },
    downloadLogParsFile(json, func) {
        dispatch(actionCreators.downloadLogParsFile(json, func))
    },
    deleteLogFile(json, func) {
        dispatch(actionCreators.deleteLogFile(json, func))
    },
    readLogParsFile(json, func, result) {
        dispatch(actionCreators.readLogParsFile(json, func, result))
    }
});

export default connect(mapState, mapDispatch)(ContentListComponent);